package com.liuceng.mps.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * EncryptUtils.java
 * 
 * @author liyuhang
 */
public class EncryptUtils {
  private static final Logger LOG = LoggerFactory.getLogger(EncryptUtils.class);

  public static String sha1(String value) {
    try {
      return hash(MessageDigest.getInstance("SHA1"), value);
    } catch (NoSuchAlgorithmException e) {
      LOG.error(e.getMessage(), e);
    }
    return null;
  }

  private static String hash(MessageDigest digest, String src) {
    return toHexString(digest.digest(src.getBytes()));
  }

  private static String toHexString(byte[] bytes) {
    char[] values = new char[bytes.length * 2];
    int i = 0;
    for (byte b : bytes) {
      values[i++] = LETTERS[((b & 0xF0) >>> 4)];
      values[i++] = LETTERS[b & 0xF];
    }
    return String.valueOf(values);
  }

  private static final char[] LETTERS = "0123456789ABCDEF".toCharArray();

  private static String byte2hex(byte b[]) {
    StringBuffer hs = new StringBuffer();
    String stmp = "";
    for (int n = 0; n < b.length; n++) {
      stmp = Integer.toHexString(b[n] & 255);
      if (stmp.length() == 1) {
        hs.append("0").append(stmp);
      } else {
        hs.append(stmp);
      }
    }
    return hs.toString().toUpperCase();
  }

  /**
   * Des可逆加密
   * 
   * @param str
   * @return
   */
  public static String encryptDes(String str) {
    return getEncryptor().encrypt(str);
  }

  public static String md5Hex(String str) {
    return DigestUtils.md5Hex(str);
  }

  public static String hashPassword(String str) {
    return md5Hex(str);
  }

  /**
   * DES解密
   * 
   * @param str
   * @return
   */
  public static String decryptDes(String str) {
    return getEncryptor().decrypt(str);
  }

  private static StandardPBEStringEncryptor getEncryptor() {
    StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
    encryptor.setAlgorithm("PBEWithMD5AndDES");
    encryptor.setPassword("INSKYE");
    return encryptor;
  }

  public static void main(String[] args) {
    System.out.println("--->     " + encryptDes("1"));
    System.out.println("--->     " + decryptDes("fTWmVSnbQoZJem8pG+FlJA=="));
  }
}
